package models

import (
	"database/sql"
	"strconv"

	"gohub/pkg/database"
)

// Article  对应一条文章数据
type Article struct {
	Title, Body string
	ID          int64
}

// 保存文章
func SaveArticleToDB(title string, body string) (int64, error) {

	// 变量初始化
	var (
		id   int64
		err  error
		rs   sql.Result
		stmt *sql.Stmt
	)

	// 1. 获取一个 prepare 声明语句
	stmt, err = database.DB.Prepare("INSERT INTO articles (`title`, `body`) VALUES(?,?)")
	// 例行的错误检测
	if err != nil {
		return 0, err
	}

	// 2. 在此函数运行结束后关闭此语句，防止占用 SQL 连接
	defer stmt.Close()

	// 3. 执行请求，传参进入绑定的内容
	rs, err = stmt.Exec(title, body)
	if err != nil {
		return 0, err
	}

	// 4. 插入成功的话，会返回自增 ID
	if id, err = rs.LastInsertId(); id > 0 {
		return id, nil
	}

	return 0, err

}
func GetArticleByID(id string) (Article, error) {
	article := Article{}
	query := "SELECT * FROM articles WHERE id = ?"
	err := database.DB.QueryRow(query, id).Scan(&article.ID, &article.Title, &article.Body)
	return article, err
}
func UpdateArticleToDB(id, title, body string) (int64, error) {
	query := "UPDATE articles SET title = ?, body = ? WHERE id = ?"

	result, err := database.DB.Exec(query, title, body, id)
	if err != nil {
		return 0, err
	}
	rowsAffected, err := result.RowsAffected()

	return rowsAffected, err
}
func (a Article) Delete() (rowsAffected int64, err error) {
	rs, err := database.DB.Exec("DELETE FROM articles WHERE `id` = " + strconv.FormatInt(a.ID, 10))

	if err != nil {
		return 0, err
	}

	//  √ 删除成功
	if n, _ := rs.RowsAffected(); n > 0 {
		return n, nil
	}
	return 0, nil
}
